package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.dao.OrderDiscussDao;
import com.qst.crop.entity.*;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.service.OrderDiscussService;
import com.qst.crop.service.OrderService;
import com.qst.crop.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author spengda
 * @date 2024/3/814:38
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDiscussService orderDiscussService;
    //分页获取所有的all1111111
    @RequestMapping("/All/{pageNum}")
    public Result<PageInfo> getOrderAll(@PathVariable("pageNum")Integer pageNum){
        PageInfo<Order> pageInfo = orderService.findAll(pageNum);


        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * @Description : 查询卖出订单
     *  * @param
     * @Return : com.qst.crop.common.Result<java.util.List<com.qst.crop.entity.SellPurchase>>
     */
    @GetMapping("selectSells")
    @ApiOperation("查询卖出订单")
    public Result<List<SellPurchase>> getSellPurchase(){
        log.info("查询卖出订单");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        log.info("name=" + username);
        List<SellPurchase> list = orderService.findAllSells(username);
        return new Result<>(true, StatusCode.OK,"查询成功",list);
    }




    @GetMapping("/selectById/{id}")
    public Result<Order> selectById(@PathVariable("id") int order_id){
        return new Result<>(true,StatusCode.OK,"查询成功!",orderService.selectById(order_id));
    }
//ok

    @GetMapping("/needs/{pageNum}")
    public Result<PageInfo> findAllNeeds(@PathVariable("pageNum")Integer pageNum){

        PageInfo<Order> pageInfo = orderService.findAllNeeds(pageNum);

        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }
    //ok
    @GetMapping("/searchNeedsByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchNeedsByKeys(@PathVariable("keys")String keys,@PathVariable("pageNum")Integer pageNum){
        PageInfo<Order> pageInfo = orderService.searchNeedsByKeys(keys,pageNum);


        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }
//ok



    @RequestMapping("/search/{type}/{pageNum}")
    public Result<PageInfo> search(@PathVariable("pageNum") Integer pageNum,@PathVariable("type") String type){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        PageInfo<Order> pageInfo = orderService.search(username,pageNum,type);

        String role = userService.getRole(username).trim();

        if(role.equals("user") || role.equals("expert")){
            pageInfo = orderService.search(username,pageNum,type);
        }else if(role.equals("admin")){
            pageInfo = orderService.searchAll(pageNum,type);
        }



        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }


    @RequestMapping("/searchAll/{type}/{pageNum}")
    public Result<PageInfo> searchAll(@PathVariable("pageNum") Integer pageNum,@PathVariable("type") String type){


        PageInfo<Order> pageInfo = orderService.searchAll(pageNum,type);



        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }
    //ok

    @RequestMapping("/searchMyGoodsByKeys/{title}/{pageNum}")
    public Result<PageInfo> searchMyGoodsByKeys(@PathVariable("pageNum") Integer pageNum, @PathVariable("title") String title){
        PageInfo<Order> pageInfo = orderService.searchMyGoodsByKeys(pageNum,title);
        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }
//ok



//    @PutMapping("/{orderId}")
//    @ApiOperation("更新商品信息")
//    public Result<Integer> updateGoods(@PathVariable("orderId")Integer id ,@RequestBody Order order){
//        order.setOrderId(id);
//        order.setUpdateTime(LocalDateTime.now());
//        return new Result<>(true,StatusCode.OK,"修改成功!",orderService.updateGoods(order));
//    }

    @PutMapping("/{id}")
//    @ApiOperation("修改农业知识")
    public Result updateGoods( @RequestBody Order order, @PathVariable("id") Integer id) {
        order.setOrderId(id);
        order.setUpdateTime(LocalDateTime.now());
        log.info("c order:{}",order);
        orderService.updateGoods(order);
        return new Result<>(true, StatusCode.OK,"修改成功");
    }
    @ApiOperation("添加")
    @RequestMapping
    public Result<Integer> add(@RequestBody Order order){
        log.info("ccc insert order:{}",order);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        order.setOwnName(username);
        order.setOrderStatus(1);

        LocalDateTime now = LocalDateTime.now();
        order.setUpdateTime(now);
        order.setCreateTime(now);

        return new Result<>(true, StatusCode.OK,"添加成功",orderService.insert(order));
    }


    @ApiOperation("更新需求")
    @PutMapping("/updateByPrimaryKey")
    public Result<Integer> updateByPrimaryKey(@RequestBody Order order){

        return new Result<>(true, StatusCode.OK,"更新成功",orderService.updateByPrimaryKey(order));
    }



    @ApiOperation("更新 ")
    @PutMapping("/updateByPrimaryKeySelective")
    public Result<Integer> updateByPrimaryKeySelective(Order order){

        return new Result<>(true, StatusCode.OK,"更新成功",orderService.updateByPrimaryKeySelective(order));
    }


    @PostMapping("/insertSelective")
    public int insertSelective(Order order){

        return orderService.insertSelective(order);
    }



    @ApiOperation("根据ID查询需求")
    @GetMapping("/selectByPrimaryKey")
    public Order selectByPrimaryKey(Integer id){
        return orderService.selectByPrimaryKey(id);
    }





    @ApiOperation("按照用户名获取")
    @GetMapping("/selectBuyByUserName")
    public Order selectBuyByUserName(String username){

        return orderService.selectBuyByUserName(username);
    }

    @ApiOperation("按照用户名获取销售订单")
    @GetMapping("/selectSellByUserName")
    public Order selectSellByUserName(String username){

        return orderService.selectSellByUserName(username);
    }


    @ApiOperation("按照用户名和类型获取订单")
    @GetMapping("/selectOrderByUsernameAndType")
    public Order selectOrderByUsernameAndType(String username,String type){
        return orderService.selectOrderByUsernameAndType(username,type);
    }


    @ApiOperation("按照订单编号获取详情")
    @GetMapping("/selectBuysDetail/{orderId}")
    //实现了个人查询的功能，设置了权限
    public Order selectBuysDetail(@PathVariable Integer orderId) {
        Result<List<Order>> listResult = this.selectBuys();
        List<Order> data = listResult.getData();
        Order result= null;
        for(Order order:data){
            if(order.getOrderId().equals(orderId)){
                result = order;
                break;
            }
        }
        return result;
    }

    @ApiOperation("按照ID获取全部订单")
    @GetMapping("/selectBuys")
    //实现了个人查询的功能，设置了权限
    public Result<List<Order>> selectBuys(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        List<Order> list=orderService.selectBuys(username);
        return new Result<>(true,StatusCode.OK,"查询成功",list);
    }




    //分页查询个人需求
    @RequestMapping("/searchMyNeedsByKeys/{content}/{pageNum}")
    public Result<PageInfo> searchMyNeedsByKeys(@PathVariable("pageNum")Integer pageNum,@PathVariable("content")String content){
        log.info("searchMyNeedsByKeys");

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        log.info("username:{}",username);
        PageInfo<Order> result=orderService.searchMyNeedsByKeys(pageNum,content,username);
        return new Result<>(true,StatusCode.OK,"查询成功",result);
    }



    @DeleteMapping("/deleteByPrimaryKey/{orderId}")
    public int deleteByPrimaryKey(@PathVariable("orderId")Integer orderId){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        OrderDeleteParams params = new OrderDeleteParams(orderId,username);
        return orderService.deleteByPrimaryKey(params);
    }


    @GetMapping("/searchAllByKeys/{keys}/{pageNum}")
    public Result<PageInfo> searchAllByKeys(@PathVariable("keys") String keys,@PathVariable("pageNum") Integer pageNum){
        PageInfo<Order> result=orderService.searchAllByKeys(keys,pageNum);
        return new Result<>(true,StatusCode.OK,"查询成功",result);

    }

    @DeleteMapping("/{id}")
    public Result<Integer> delOrderById(@PathVariable("id") Integer id){
        return new Result<>(true,StatusCode.OK,"删除成功",orderService.delOrderById(id));
    }

    @GetMapping("/goods/{pageNum}")
    public Result<PageInfo> findAllGoods(@PathVariable("pageNum")Integer pageNum){
        PageInfo<Order> result=orderService.findAllGoods(pageNum);
        return new Result<>(true,StatusCode.OK,"查询成功",result);

    }

    @GetMapping("/searchGoodsByKeys/{keys}/{pagekNum}")
    public Result<PageInfo> searchGoodsByKeys(@PathVariable("keys")String keys, @PathVariable("pageNum")Integer pageNum){
        PageInfo<Order> result=orderService.searchGoodsByKeys(keys,pageNum);
        return new Result<>(true,StatusCode.OK,"查询成功",result);

    }

    @PutMapping("/takeUpOrder/{id}")
    public Result<Integer> takeUpOrder(@PathVariable("id") Integer id){
        return new Result<>(true,StatusCode.OK,"上架成功", orderService.takeUpDownOrder(id,0));
    }

    @PutMapping("/takeDownOrder/{id}")
    public Result<Integer> takeDownOrder(@PathVariable("id") Integer id){
        return new Result<>(true,StatusCode.OK,"下架成功", orderService.takeUpDownOrder(id,1));
    }

    /**
     * 获取商品详情界面的商品轮播图
     * database：tb_order_picture
     * @param id
     * @return
     */
    @GetMapping("/getCarousel/{id}")
    public Result<List<String>> getOrderCarousel(@PathVariable Integer id){
        return new Result<>(true,StatusCode.OK,"获取轮播图成功",orderService.getOrderCarousel(id));
    }


    @PostMapping("/leaveComments")
    public Result<Integer> leaveComments(@RequestBody OrderDiscuss orderDiscuss){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        orderDiscuss.setUserName(username);
        orderDiscuss.setUpdateTime(LocalDateTime.now());

        return new Result<>(true,StatusCode.OK,"添加评论成功", orderService.leaveComments(orderDiscuss));
    }


    @PutMapping("/commentsNumAdd")
    public Result<Integer> commentsNumAdd(String discussUsername,Integer newNum){
        return new Result<>(true,StatusCode.OK,"用户评论数量增加成功", orderService.commentsNumAdd(discussUsername,newNum));
    }


    // 添加新的评论
    @PostMapping("/")
    public void addOrderDiscuss(@RequestBody OrderDiscuss orderDiscuss) {
        orderDiscussService.addOrderDiscuss(orderDiscuss);
    }



}
